﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Z1029.PhiPlayer.OpenSource
{
    public class ProgressControl : MonoBehaviour
    {
        const bool useDeltaTime = false;

        public double startTime;
        public double lastDspTime;
        public double deltaDspTime;
        public double targetTime;
        public double pauseTime;
        [SerializeField]
        double nowTime;

        int frameCounter;

        void Start()
        {
            frameCounter = 0;
        }

        public void StartAudio()
        {
            startTime = AudioSettings.dspTime;
            lastDspTime = startTime;
        }

        public void PauseAudio()
        {
            pauseTime = AudioSettings.dspTime;
        }

        public void ResumeAudio()
        {
            frameCounter = 0;
            startTime += AudioSettings.dspTime - pauseTime;
            lastDspTime = AudioSettings.dspTime;
        }

        void Update()
        {
            if (!PauseGame.pause && PauseGame.start)
            {
                if (!useDeltaTime)
                {
                    targetTime = AudioSettings.dspTime - startTime;
                    if (frameCounter >= 60)
                    {
                        frameCounter = 0;
                        deltaDspTime = AudioSettings.dspTime - lastDspTime;
                        lastDspTime = AudioSettings.dspTime;
                    }

                    if (deltaDspTime <= 0)
                    {
                        if (targetTime > nowTime)
                            nowTime = targetTime;
                    }
                    else
                    {
                        if (nowTime + deltaDspTime / 60.0 < targetTime)
                        {
                            if (targetTime > nowTime) nowTime += deltaDspTime / 60.0;
                        }
                        else
                        {
                            nowTime = targetTime;
                            //print("Sync Time");
                            //SyncMusic();
                        }
                    }
                    frameCounter++;
                }
                else nowTime += Time.smoothDeltaTime;

                LevelController.nowTime = nowTime;
            }
        }
    }
}